package com.fzu.ess.sys.utils;

import com.fzu.ess.sys.entity.User;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Random;

/**
 * Created by ercha on 2015/10/22.
 */
public class PasswordUtils {

    private static int hashIterations = 2;
    private static int minValue = 100000;
    private static int maxValue = 1000000;

    static {
        Properties properties = new Properties();
        InputStream in = Object.class.getResourceAsStream("/config.properties");
        try{
            properties.load(in);
            hashIterations = Integer.parseInt(properties.getProperty("hashIterations").trim());
        } catch(IOException e){
            e.printStackTrace();
        }
    }

    public static int getHashIterations(){
        System.out.println("hashIterations: " + hashIterations);
        return hashIterations;
    }

    //md5 2 次
    public static void encryptByMd5(String password, User user){
        user.setSalt((new SecureRandomNumberGenerator()).nextBytes().toHex());
        user.setPassword(new SimpleHash("md5", password, ByteSource.Util.bytes(user.getUsername()+user.getSalt()), hashIterations).toHex());
    }

    //返回一个 6 位数的新密码
    public static String getRandomPassword(){
        return new Random().nextInt(maxValue) + minValue + "";
    }
}
